#pragma once 
#include <iostream>
#include <string>

#include <cerrno>
#include <cstdio>
#include <cstring>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "log.hpp"

class TcpServer
{
public:
    TcpServer(uint16_t port, std::string ip = "")
        :_port(port)
        ,_ip(ip)
        ,_sock(-1)
    {}

    void initServer()
    {
        // 创建socket
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_sock < 0)
        {
            logMessage(FATAL, "%d:%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "sock: %d", _sock);

    // bind
    struct sockaddr_in local;
    memset(&local, 0, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(_port);
    local.sin_addr.s_addr = _ip.empty() ? INADDR_ANY : inet_addr(_ip.c_str());
    if (bind(_sock, (struct sockaddr*)&local, sizeof(local)) < 0)
    {
        logMessage(FATAL, "bind error, %d:%s", errno, strerror(errno));
        exit(3);
    }

        // tcp面向连接的，通信前要先建立连接

    }

    void start()
    {

    }

    ~TcpServer(){}
private:
    uint16_t _port;
    std::string _ip;
    int _sock;
};
